﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web;

namespace MvcPatch
{
    public class AreaControllerFactory : IControllerFactory
    {
        private static ControllerTypeCache s_controllerTypeCache = new ControllerTypeCache();

        public virtual IController CreateController(RequestContext requestContext, string controllerName)
        {
            Type controllerType = this.GetControllerType(requestContext, controllerName);
            IController controller = this.GetControllerInstance(requestContext, controllerType);
            return controller;
        }

        protected virtual Type GetControllerType(RequestContext requestContext, string controllerName)
        {
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }
            if (String.IsNullOrEmpty(controllerName))
            {
                throw new ArgumentNullException("controllerName", "controllerName is null or empty");
            }

            string area = (string)requestContext.RouteData.Values["area"];
            if (String.IsNullOrEmpty(area)) area = "";

            return s_controllerTypeCache.Get(area, controllerName);
        }

        protected virtual IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                var message = String.Format("Controller is not found for url: {0}", requestContext.HttpContext.Request.Path);
                throw new HttpException(404, message);                    
            }

            if (!typeof(IController).IsAssignableFrom(controllerType))
            {
                var message = String.Format("{0} is not a controller type.", controllerType);
                throw new ArgumentException(message, "controllerType");
            }
            try
            {
                return (IController)Activator.CreateInstance(controllerType);
            }
            catch (Exception ex)
            {
                var message = String.Format("Error occurred when creating {0}", controllerType);
                throw new InvalidOperationException(message, ex);
            }
        }

        public virtual void ReleaseController(IController controller)
        {
            IDisposable disposable = controller as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }
    }
}
